package com.xzg.erp.product.web;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzg.erp.common.BusinessException;
import com.xzg.erp.common.Constants;
import com.xzg.erp.product.entity.ProductType;
import com.xzg.erp.product.entity.dto.ProductTypeDto;
import com.xzg.erp.product.service.IProductTypeService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 产品类型表 前端控制器
 * </p>
 *
 * @author qwc
 * @since 2025-02-12
 */
@RestController
@RequestMapping("/productType")
public class ProductTypeController {

    @Autowired
    private IProductTypeService productTypeService;

    @PostMapping("/add")
    public ResponseEntity add(@Valid @RequestBody ProductType type) {
        int loginId = StpUtil.getLoginIdAsInt();
        ProductType one = productTypeService.getOne(Wrappers.<ProductType>lambdaQuery().eq(ProductType::getName, type.getName()).eq(ProductType::getDeleted, Constants.UN_DELETED));
        if (Objects.nonNull(one)) {
            throw new BusinessException(HttpStatus.CONFLICT, Constants.DATA_EXIT);
        }
        type.setCreatedBy(loginId);
        type.setCreatedAt(LocalDateTime.now());
        productTypeService.save(type);
        return ResponseEntity.ok(Constants.SUCCESS);
    }

    @PostMapping("/page")
    public ResponseEntity page(@RequestBody ProductTypeDto dto) {
        Page<ProductType> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        Page<ProductType> page1 = productTypeService.page(page,Wrappers.<ProductType>lambdaQuery().eq(ProductType::getDeleted,Constants.UN_DELETED).orderByDesc(ProductType::getCreatedAt));
        return ResponseEntity.ok(page1);
    }

    @PostMapping("/delete/{ids}")
    public ResponseEntity delete(@PathVariable List<Integer> ids) {
        productTypeService.logicDelete(ids);
        return ResponseEntity.ok(Constants.SUCCESS);
    }

    @PostMapping("/update")
    public ResponseEntity update(@RequestBody ProductType type) {
        int loginId = StpUtil.getLoginIdAsInt();
        type.setUpdatedBy(loginId);
        type.setUpdatedAt(LocalDateTime.now());
        productTypeService.updateById(type);
        return ResponseEntity.ok(Constants.SUCCESS);
    }

}
